package com.hong.service_product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hong.fy_common_commomutil.common.result.Result;
import com.hong.fy_model.model.product.ProductEntity;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


import com.hong.service_product.mapper.ProductMapper;

import com.hong.service_product.service.ProductService;


@Service("productService")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductEntity> implements ProductService {

    //新增商品
    @CachePut(value = "product", key = "#product.id")
    @Override
    public Boolean  addProduct(ProductEntity product) {
        boolean flag = this.save(product);
        return flag;
    }

    //根据商品ID逻辑删除商品
    @CacheEvict(value = "product", allEntries = true)
    @Override
    public Boolean deleteProduct(Integer id) {
        boolean flag = this.removeById(id);
        return flag;
    }

    //更新商品
    @CacheEvict(value = "product", key = "#product.productId")
    @Override
    public Boolean updateProduct(ProductEntity product) {
        //查询商品是否存在
        ProductEntity productEntity = this.getById(product.getProductId());
        if (productEntity == null) {
            return false;
        }
        boolean flag = this.updateById(product);
        return flag;
    }

    //查询分页数据
    @Cacheable(value = "product", key = "#pageNum + '_' + #limit")
    @Override
    public IPage<ProductEntity> findListByPage(Integer pageNum, Integer limit) {
        Page<ProductEntity> page = new Page<>(pageNum, limit);
        IPage<ProductEntity> iPage = this.page(page);
        return iPage;

    }

    //根据商品ID查询商品
    @Cacheable(value = "product", key = "#id")
    @Override
    public ProductEntity getProductById(Integer id) {
        ProductEntity productEntity = this.getById(id);
        productEntity.setViewCount(productEntity.getViewCount() + 1);
        this.updateById(productEntity);
        return productEntity;
    }

    //根据商品类别分页查询商品
    @Override
    public IPage<ProductEntity> getByCategoryId(Integer categoryId, Integer pageNum, Integer limit) {
        Page<ProductEntity> page = new Page<>(pageNum, limit);
        IPage<ProductEntity> iPage = this.page(page, new LambdaQueryWrapper<ProductEntity>().eq(ProductEntity::getCategoryId, categoryId));
        return iPage;
    }

    @Override
    public Result upload(ProductEntity product) {
        return null;
    }
}